package com.chat.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.chat.bean.WsMessageDTO;
import com.chat.websocket.WebsocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 *
 * 需要开启广播模式，默认是集群模式
 * messageModel = MessageModel.BROADCASTING
 */
@Slf4j
@Component
@RocketMQMessageListener(
        topic = "wsMessageTopic",
        consumerGroup = "miniChatGroup",
        messageModel = MessageModel.BROADCASTING
)
public class WsMessageConsumer implements RocketMQListener<String> {

    private final WebsocketServer websocketServer;

    @Autowired
    public WsMessageConsumer(WebsocketServer websocketServer) {
        this.websocketServer = websocketServer;
    }

    @Override
    public void onMessage(String json) {
        log.info("ws消息推送，消费端测试，数据：【{}】", json);
        WsMessageDTO wsMessageDTO = JSON.parseObject(json, WsMessageDTO.class);
        websocketServer.sendMessage(wsMessageDTO.getUid(), wsMessageDTO.getMsg());
    }
}
